const jwt = require('jsonwebtoken');

const SECRET = "layu-2324";
const time = '1h';
const prefix = 'Bearer ';

/**
 * 生成token
 * @param {*} data 生成token的用户信息
 * @returns 
 */
function createToken(data) {
    try {
        const token = jwt.sign(data, SECRET, {
            expiresIn: time
        })
        return Promise.resolve(token);
    } catch (error) {
        return Promise.reject(error);
    }
    
}

/**
 * 
 * @param {*} token 
 * @returns 
 */
function TokenIsVerify(token) {
    const index = token.indexOf(prefix);
    let formatToken = '';
    if( index < 0 ){
        return Promise.reject('invalid token');
    }else{
        formatToken = token.replace(prefix, '');
    }
    const decoded = jwt.verify(formatToken, SECRET);
    return Promise.resolve(decoded);
}

exports.createToken = createToken;
exports.TokenIsVerify = TokenIsVerify;